package com.tencent.qcloud.timchat;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.qcloud.presentation.business.InitBusiness;
import com.tencent.qcloud.presentation.business.LoginBusiness;
import com.tencent.qcloud.presentation.event.FriendshipEvent;
import com.tencent.qcloud.presentation.event.GroupEvent;
import com.tencent.qcloud.presentation.event.MessageEvent;
import com.tencent.qcloud.presentation.event.RefreshEvent;
import com.tencent.qcloud.timchat.model.ImChatUser;
import com.tencent.qcloud.timchat.model.UserInfo;
import com.tencent.qcloud.timchat.model.UserInfoProvider;
import com.tencent.qcloud.timchat.ui.HomeActivity;
import com.tencent.qcloud.timchat.utils.PushUtil;
import com.tencent.qcloud.tlslibrary.service.TLSService;
import com.tencent.qcloud.tlslibrary.service.TlsBusiness;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RequestExecutor;
import com.yanzhenjie.permission.SettingService;

import java.util.List;

import static android.content.Context.NOTIFICATION_SERVICE;

public class ImStart implements TIMCallBack {
    private AppCompatActivity activity;
    private static final String TAG = ImStart.class.getSimpleName();

    public void onCreate(Activity activity) {
        this.activity = (AppCompatActivity) activity;
        clearNotification();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermission();
        } else {
            init();
        }
    }

    private void init() {
        //初始化IMSDK
        InitBusiness.start(activity, 1);
        //初始化TLS
        TlsBusiness.init(activity);
        String id = TLSService.getInstance().getLastUserIdentifier();
        if (TextUtils.isEmpty(id) || TextUtils.isEmpty(TLSService.getInstance().getUserSig(id))) {
            ImChatUser chatUser = ImInit.getImChatUser(UserInfoProvider.USER_SELF);
            if (chatUser != null) {
                UserInfo.getInstance().setId(chatUser.getImUserName());
                UserInfo.getInstance().setUserSig(chatUser.getImUserPsw());
            }
        } else {
            UserInfo.getInstance().setId(id);
            UserInfo.getInstance().setUserSig(TLSService.getInstance().getUserSig(id));
        }
        navToHome();
    }

    public void navToHome() {
        //登录之前要初始化群和好友关系链缓存
        TIMUserConfig userConfig = new TIMUserConfig();
        userConfig.setUserStatusListener(
                new TIMUserStatusListener() {
                    @Override
                    public void onForceOffline() {
                        // 挤掉线
                    }

                    @Override
                    public void onUserSigExpired() {
                        //票据过期，需要重新登录
                    }
                })
                .setConnectionListener(new TIMConnListener() {
                    @Override
                    public void onConnected() {
                        Log.i(TAG, "onConnected");
                    }

                    @Override
                    public void onDisconnected(int code, String desc) {
                        Log.i(TAG, "onDisconnected");
                    }

                    @Override
                    public void onWifiNeedAuth(String name) {
                        Log.i(TAG, "onWifiNeedAuth");
                    }
                });

        //设置刷新监听
        RefreshEvent.getInstance().init(userConfig);

        userConfig = FriendshipEvent.getInstance().init(userConfig);
        userConfig = GroupEvent.getInstance().init(userConfig);
        userConfig = MessageEvent.getInstance().init(userConfig);
        TIMManager.getInstance().setUserConfig(userConfig);
        LoginBusiness.loginIm(UserInfo.getInstance().getId(), UserInfo.getInstance().getUserSig(), this);
    }

    /**
     * 跳转到登录界面
     */
    public void navToLogin() {
        Toast.makeText(activity, R.string.login_error, Toast.LENGTH_SHORT).show();
    }

    /**
     * imsdk登录失败后回调
     */
    @Override
    public void onError(int i, String s) {
        Log.e(TAG, "login error : code " + i + " " + s);
        switch (i) {
            case 6208:
                //离线状态下被其他终端踢下线
                new AlertDialog.Builder(activity)
                        .setCancelable(false)
                        .setMessage(activity.getString(R.string.kick_logout))
                        .show();
                break;
            case 6200:
                Toast.makeText(activity, R.string.login_error_timeout, Toast.LENGTH_SHORT).show();
                break;
            default:
                navToLogin();
                break;
        }

    }

    /**
     * imsdk登录成功后回调
     */
    @Override
    public void onSuccess() {
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
        String deviceMan = Build.MANUFACTURER;
        //注册小米和华为推送
        Log.d(TAG, "imsdk env " + TIMManager.getInstance().getEnv());

        Intent intent = new Intent(activity, HomeActivity.class);
        activity.startActivity(intent);
    }

    /**
     * 清楚所有通知栏通知
     */
    private void clearNotification() {
        NotificationManager notificationManager = (NotificationManager) activity.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    private void requestPermission() {
        AndPermission.with(activity).permission(Permission.Group.STORAGE, Permission.Group.CAMERA)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        init();
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(activity, permissions)) {
                            List<String> permissionNames = Permission.transformText(activity, permissions);
                            String message = activity.getString(R.string.im_need_permission, TextUtils.join("\n", permissionNames));

                            final SettingService settingService = AndPermission.permissionSetting(activity);
                            new AlertDialog.Builder(activity)
                                    .setCancelable(false)
                                    .setMessage(message)
                                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            settingService.execute();
                                            dialog.dismiss();
                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            settingService.cancel();
                                            dialog.dismiss();
                                        }
                                    }).show();
                        }
                    }
                })
                .start();
    }
}
